package com.zyy.study.IO;

import org.junit.Test;

import java.io.*;

public class StreamDemo {
    /**
     * 测试字节输入流
     */
    @Test
    public void t1() {
        try (FileInputStream inputStream = new FileInputStream("input.txt");) {
            int c;
            while ((c=inputStream.read()) != -1) {
                System.out.print((char)c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试字节输出流
     */
    @Test
    public void t2() {
        try(FileOutputStream outputStream = new FileOutputStream("output.txt");
            FileInputStream inputStream = new FileInputStream("input.txt");) {
            int c;
            while ((c = inputStream.read()) != -1) {
                outputStream.write(c);
                System.out.print((char)c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试字符输入流
     */
    @Test
    public void t3() {
        int c;
        try(FileReader fileReader = new FileReader("input.txt")){
            while ((c = fileReader.read()) != -1) {
                System.out.print((char) c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试缓冲字节流
     */
    @Test
    public void t4() {
        int c;
        try(BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("input.txt"));
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("output.txt"));){
            while ((c = inputStream.read()) != -1) {
                outputStream.write(c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试字节数组缓冲字节流
     */
    @Test
    public void t5() {
        byte[] bytes = new byte[4 * 1024];
        int c;
        try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("input.txt"));
             final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("output.txt"))) {
            while ((c = inputStream.read(bytes)) != -1) {
                System.out.println(c);
                //读取多少字节到数组，就写多少字节
                outputStream.write(bytes, 0, c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
